package dq.study.jvm.classloader.instance;

import com.sun.deploy.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dongqun
 * @version 1.0.0
 * @since 2020/12/31 13:30:00
 */
public class OverrideFindClassMethodClassLoader extends ClassLoader {

    private Map<String, String> classes = new HashMap<>();

    public OverrideFindClassMethodClassLoader() {
        classes.put("dq.study.jvm.classloader.instance.TestA", "D:\\PersonProject\\test-field\\out\\production\\jvm\\dq\\study\\jvm\\classloader\\instance\\TestA.class");
        classes.put("dq.study.jvm.classloader.instance.TestB", "D:\\PersonProject\\test-field\\out\\production\\jvm\\dq\\study\\jvm\\classloader\\instance\\TestB.class");
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classpath = classes.get(name);
        if (classpath == null) {
            throw new ClassNotFoundException();
        }
        byte[] classdata = getClassByte(classpath);
        return defineClass(null, classdata, 0, classdata.length);
    }

    private byte[] getClassByte(String classpath) {
        try (FileInputStream fileInputStream = new FileInputStream(classpath);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileInputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }
}
